<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Communication between an iframe and its parent window</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
    </head>
    <body>
        <iframe id="frame" src="iframe.html" style="border: none; height: 350px; width: 100%"></iframe>

        <div style="padding: 1rem">
            <h2>Window</h2>
            <button
                id="sendToIframe"
                type="button"
                style="border: none; background-color: #3182ce; color: #fff; padding: 0.25rem 0.5rem"
            >
                Send to iframe
            </button>
            <div
                id="message"
                style="border: 1px solid #cbd5e0; height: 12rem; margin: 0.5rem 0; overflow: auto; padding: 0.5rem"
            ></div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const messageEle = document.getElementById('message');
                const frameEle = document.getElementById('frame');

                window.addEventListener('message', function (e) {
                    const data = JSON.parse(e.data);
                    const date = new Date(data.date).toLocaleTimeString('en-US');

                    messageEle.innerHTML = `Receive "${data.message}" at ${date}<br>` + messageEle.innerHTML;
                });

                document.getElementById('sendToIframe').addEventListener('click', function () {
                    const message = JSON.stringify({
                        message: 'Hello from window',
                        date: Date.now(),
                    });
                    frameEle.contentWindow.postMessage(message, '*');
                });
            });
        </script>
    </body>
</html>
